package com.cdy.jxc_project.controller;

import com.cdy.jxc_project.domain.TAdmin;
import com.cdy.jxc_project.domain.vo.TAdminLoginVo;
import com.cdy.jxc_project.json.R;
import com.cdy.jxc_project.req.AuthToAdminReq;
import com.cdy.jxc_project.service.TAdminService;
import com.cdy.jxc_project.utils.AddSysLog;
import com.cdy.jxc_project.utils.SessionKey;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

/*
 * @Project:jxc_project
 * @Author:cdy(缘生)
 * @Motto:放下杂念,只为迎接明天更好的自己
 * @Date:2023/4/20 14:23
 * */

@RestController
@RequestMapping("/tAdmin")
public class TAdminController {

    @Resource
    private TAdminService tAdminService;
    @Resource
    private DefaultKaptcha defaultKaptcha;
    @AddSysLog("登录")
    @PostMapping("/login")
    public R login(@RequestBody TAdminLoginVo tAdminLoginVo, HttpSession session) {

        String yzmCode = tAdminLoginVo.getCode();
        if (yzmCode == null) {
            return R.error().message("验证码有误");
        } else {
            Object attribute = session.getAttribute(SessionKey.yzmKey);

            if (!yzmCode.equals(attribute)) {
                return R.error().message("验证码有误");
            }

            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken =
                    new UsernamePasswordToken(tAdminLoginVo.getUsername(), tAdminLoginVo.getPassword());

            //认证,程序会执行我们的认证流程
            try {
                subject.login(usernamePasswordToken);
            } catch (UnknownAccountException ex) {
                return R.error().message("用户名错误");
            } catch (IncorrectCredentialsException ex) {
                return R.error().message("密码错误");
            }catch (Exception e){
                return R.error().message("密码错误2");
            }
            boolean authenticated = subject.isAuthenticated();
            System.out.println("是否认证成功:" + authenticated);
            if (authenticated) {
                Object principal = subject.getPrincipal();
                Object user = SecurityUtils.getSubject().getSession().getAttribute(SessionKey.adminKey);
                return R.ok().message("登录成功").data("user", user);
            } else {
                return R.error().message("认证失败");
            }
        }
    }

    // 生成验证码,获取动态生成的验证码？
    @GetMapping("/verifyCode")
    public void loginVerifyCode(HttpServletRequest request, HttpServletResponse response) {
        // 定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        //-------------------生成验证码 begin --------------------------

        //获取验证码文本内容
        String text = defaultKaptcha.createText();
        System.out.println("验证码内容：" + text);
        //将验证码文本内容放入session
        request.getSession().setAttribute(SessionKey.yzmKey, text);
        //根据文本验证码内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //输出流输出图片，格式为jpg
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //-------------------生成验证码 end --------------------------
    }
    @AddSysLog
    @PostMapping("/queryAll")
    public  R queryAll(){
        List<TAdmin> adminList = tAdminService.queryAll();
        return  R.ok().message("查询成功").data("adminList",adminList );
    }

    @DeleteMapping("/deleteTAdmin/{id}")
    public R deleteTAdmin(@PathVariable("id") Integer id){
        if (tAdminService.deleteTAdmin(id)>0){
            return R.ok().message("删除成功");
        }else {
            return R.error().message("错误");
        }
    }
    @AddSysLog
    @PostMapping("/insertAndUpdateTAdmin")
    public R insertAndUpdateTAdmin(@RequestBody TAdmin tAdmin){
        try{
            if (tAdmin.getId()==null){
                if (tAdmin.getEnabled()==null){
                    tAdmin.setEnabled(1);
                }
                tAdminService.insertTAdmin(tAdmin);
                return R.ok().message("保存成功");
            }else {
                tAdminService.updateTAdmin(tAdmin);
                return R.ok().message("修改成功");
            }

        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("程序出错");
        }
    }
    @PostMapping("/authToAdmin")
    public R authToAdmin(@RequestBody AuthToAdminReq req){
        try{
            Integer aid = req.getAid();
            System.out.println(aid);
            System.out.println(req.getRids()+"====================================");
            if (null == aid) {
                return R.error().message("角色id不能为空");
            } else {
                return tAdminService.authToAdmin(aid, req.getRids());
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("程序出错");
        }
    }

    //查询当前用户角色
    @PostMapping("/getAdminRole/{id}")
    public  R getAdminRole(@PathVariable Integer id){
        List<Integer> adminRoleList = tAdminService.getAdminRole(id);
        return  R.ok().message("查询成功").data("adminRoleList",adminRoleList );
    }
}
